package com.vv.tools.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import com.vv.tools.common.message.CustomerBizException;
import com.vv.tools.common.message.ResultEnum;
import com.vv.tools.modules.sys.dao.CaptchaMapper;
import com.vv.tools.modules.sys.entity.Captcha;
import com.vv.tools.modules.sys.service.CaptchaService;

import java.awt.image.BufferedImage;
import java.time.LocalDateTime;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 系统验证码 服务实现类
 * </p>
 *
 * @author vv
 * @since 2025-02-19
 */
@Service
public class CaptchaServiceImpl extends ServiceImpl<CaptchaMapper, Captcha> implements CaptchaService {

    @Autowired
    private Producer producer;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new CustomerBizException(ResultEnum.VALID_EXCEPTION, "uuid");
        }
        //生成文字验证码
        String code = producer.createText();

        Captcha captcha = new Captcha();
        captcha.setUuid(uuid);
        captcha.setCode(code);
        //5分钟后过期
        captcha.setExpireTime(LocalDateTime.now().plusMinutes(5L));
        this.save(captcha);

        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        Captcha captcha = this.getOne(Wrappers.lambdaQuery(Captcha.class)
            .eq(Captcha::getUuid, uuid)
            .gt(Captcha::getExpireTime, LocalDateTime.now())
            .groupBy(Captcha::getUuid)
        );
        if (captcha == null) {
            return false;
        }

        //删除验证码
        this.removeById(captcha.getId());

        return captcha.getCode().equalsIgnoreCase(code) && captcha.getExpireTime().isAfter(LocalDateTime.now());
    }

}
